package captcha

import (
	"gitee.com/zhucheer/orange/app"
	"gitee.com/zhucheer/orange/utils"
	"strings"
)

var captchaSessionName = "ORANGE-CAPTCHA"

func init() {
	ranTag := utils.ShortTag(utils.GetRandStr(2), 1)
	captchaSessionName += ranTag
}

func CaptchaImgByte(c *app.Context, n int, size ...int) (text string, imgByte []byte) {
	text, imgByte = createCode(c, n, size...)
	return
}

func CaptchaImgShow(c *app.Context, n int, size ...int) error {
	_, imgByte := createCode(c, n, size...)

	c.ResponseHeader().Set("Content-Type", "image/png")
	return c.ResponseWrite(imgByte)
}

func CaptchaVerify(c *app.Context, code string) bool {

	codeMd5 := utils.Md5ToString(strings.ToUpper(code))
	sessionCode := c.Session().Get(captchaSessionName)

	if codeMd5 == sessionCode {
		c.Session().Delete(captchaSessionName)
		return true
	}
	return false
}

func createCode(c *app.Context, n int, size ...int) (text string, imgByte []byte) {
	text = utils.GetRandStr(n)
	textMd5 := utils.Md5ToString(strings.ToUpper(text))
	width := 180
	height := 60
	if len(size) >= 2 {
		width = size[0]
		height = size[1]
	}

	c.Session().Set(captchaSessionName, textMd5)
	imgByte = ImgText(width, height, text)

	return text, imgByte
}
